package com.otitan.la.forest.system.util;

import cn.hutool.core.util.StrUtil;
import com.otitan.la.forest.system.dto.FileDTO;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;

/**
 * @Description:    文件工具类
 * @Author:        Sunke
 * @CreateDate:     2020/10/15 0015 10:46
 * @UpdateUser:     Sunke
 * @UpdateDate:     2020/10/15 0015 10:46
 * @UpdateRemark:   修改内容
 * @Version:        1.0
 */
@Component
public class FileUtil {

    private static String filePath;


//    /**
//     * @Description: 文件工具类
//     * @Author: xiazw
//     * @CreateDate: 2020/6/16 9:40
//     */
//    public static FileDTO upfile(MultipartFile file, String path) throws Exception {
//        path = filePath + path;
//        File directory = new File(path);
//        if (!directory.exists()) {
//            directory.mkdirs();
//        }
//        String name = file.getOriginalFilename();
//        String fileType = name.substring(name.lastIndexOf("."));
//        String uniqueCode = UUID.randomUUID().toString();
//        String fileName = uniqueCode + (name != null && name.lastIndexOf(".") != -1 ? fileType : "");
//
//        String filePath = path + fileName;
//        // 转存文件
//        file.transferTo(new File(filePath));
//        FileDTO upfileDTO = new FileDTO();
//        upfileDTO.setFileName(fileName);
//        upfileDTO.setFilePath(filePath);
//        return upfileDTO;
//    }

//   /**
//   * 文件上传
//   * @author Sunke
//   * @param [file]
//   * @return com.otitan.la.forest.system.dto.FileDTO
//   * @exception
//   * @date 2020/10/15 0015 10:51
//   */
//    public static FileDTO upfile(MultipartFile file) throws Exception {
//
//        ServletRequestAttributes ra = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
//        HttpServletRequest request = ra.getRequest();
//        String username = request.getHeader("username");
//        username = StrUtil.isEmpty(username) ? "sysman" : username;
//        String fileOriginalFilename = file.getOriginalFilename();
//
//
//        String fileType = null;
//        if (fileOriginalFilename.lastIndexOf(".") > -1) {
//            fileType = fileOriginalFilename.substring(fileOriginalFilename.lastIndexOf(".") + 1);
//        }
//
////        InputStream fileInputStream = file.getInputStream();
////        Set<MetaData> metaDataSet = new HashSet<>();
////        metaDataSet.add(new MetaData("author", username));
////        StorePath txt = fastFileStorageClient.uploadFile(fileInputStream, file.getSize(), fileType, metaDataSet);
//        // 返回上传结果
//        FileDTO upfileDTO = new FileDTO();
//        upfileDTO.setFileName(fileOriginalFilename);
//        upfileDTO.setFilePath("");
//        return upfileDTO;
//    }

    /**
    * 文件下载
    * @author Sunke
    * @param  [response, fastFileStorageClient, filePath, fileName]
    * @return void
    * @exception
    * @date 2020/10/15 0015 10:53
    */
    public static void downloadFile(HttpServletResponse response, String filePath, String fileName) throws Exception {

        String[] split = filePath.split("/", 2);
//        byte[] bytes = fastFileStorageClient.downloadFile(split[0], split[1], new DownloadByteArray());
//        if (bytes == null || bytes.length == 0) {
//            throw new Exception("文件不存在或文件已删除！");
//        }
//        FileInfo fileInfo = fastFileStorageClient.queryFileInfo(split[0], split[1]);

        // 设置response的Header
        setResponseContentDisposition(response, fileName);

//        response.addHeader("Content-Length", "" + fileInfo.getFileSize());
        OutputStream stream = new BufferedOutputStream(response.getOutputStream());
        response.setContentType("application/octet-stream");
        //输出流开始写出文件（FileUtils是Apache下的工具类可以直接调用）
//        stream.write(bytes);
        //刷新流
        stream.flush();
    }


    public static void setResponseContentDisposition(HttpServletResponse response, String fileName) {
        // 清空response
        response.reset();

        // 创建显示内容
        StringBuilder contentDisposition = new StringBuilder("attachment;");
        // 如果附件不为null;
        if (fileName != null) {
            // 通过UTF8字符以及URL方式来编码文件名
            String filedisplay = fileName;
            try {
                filedisplay = URLEncoder.encode(fileName, "UTF-8");
            } catch (UnsupportedEncodingException e) {
                // Ignore
            }
            // 添加标准文件名
            contentDisposition.append("filename=").append(fileName).append(";");
            // 添加UTF8格式名
            // 主要为了防止部分浏览器下的文件名乱码（参见https://tools.ietf.org/html/rfc6266）
            contentDisposition.append("filename*=utf-8''").append(filedisplay);
        }
        // 输出文件名
        response.addHeader("Content-Disposition", contentDisposition.toString());
    }
}
